import { login, getInfo, register } from '@/api/login'
import { getToken, setToken, removeToken, getCacheInfo, cacheInfo, removeCacheInfo } from '@/utils/auth'
import defAva from '@/assets/images/img.png'


const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: defAva,
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            setToken(res.token)
            this.token = res.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      register(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const password_confirmation = userInfo.password
        return new Promise((resolve, reject) => {
          register({username, password, password_confirmation}).then(res => {
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res[0] || {}
            cacheInfo('currUser',user)
            // const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            this.roles = ['ROLE_DEFAULT']
            this.name = user.user_name
            // this.avatar = avatar;
            resolve(user)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          // logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeCacheInfo()
            removeToken()
            resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    }
  })

export default useUserStore
